<?php
namespace Common\Model;

use Think\Model;

class ProblemAnswerModel extends  CommonModel {

	public $tableName = 'problem_answer';

	//渠道推荐列表
	public function get_problem_answer_list(array $params){
		$ProblemModel = D("Problem");

		$where = [];
		$params['date']?$where['a.create_date'] = [['EGT', $params['date'][0]], ['ELT', $params['date'][1]]]:"";
		$params['pid']?$where['b.pid'] = $params['pid']:"";
		$params['channel_id']?$where['a.channel_id'] = $params['channel_id']:"";
		$params['channel_name']?$where['b.channel_name|c.channel_name'] = ["LIKE","%{$params['channel_name']}%"]:"";
		$pagesize = empty($params['pageSize']) ? '20' : $params['pageSize'];

		$count = $this
			->alias("a")
			->where($where)
			->join("LEFT JOIN tp_channel b ON b.id = a.channel_id")
			->join("LEFT JOIN tp_channel c ON c.id = b.pid")
			->count();
		$Page = new \Think\Page($count, $pagesize);
		$limit = $Page->firstRow . ',' . $Page->listRows;
		$field = "a.*,b.channel_name,c.channel_name as pid_channel_name,DATE_FORMAT(FROM_UNIXTIME(a.create_time), '%Y-%m-%d %H:%i') as create_time";
		$list = $this
			->alias("a")
			->field($field)
			->where($where)
			->join("LEFT JOIN tp_channel b ON b.id = a.channel_id")
			->join("LEFT JOIN tp_channel c ON c.id = b.pid")
			->limit($limit)
			->order($params['order']?$params['order']:"a.id desc")
			->select();
		$problemData = [
			'status' => 1,
			'order'  => 'a.sort asc'
		];
		$problem_field = "a.problem_name,a.id as problem_id,a.type,a.answer_options,NULL as content";
		$problem_result = $ProblemModel->get_problem_list($problemData,$problem_field);
		$problem_list = $problem_result['list'];
		foreach ($problem_list as $key => $val) {
			$val['answer_options'] = json_decode($val['answer_options'],true);
			$problem_list[$key] = $val;
		}
		$problem_list = array_column($problem_list,NULL,'problem_id');
		foreach($list as $a_key=>$a_val){
			$a_val['answer_json'] = json_decode($a_val['answer_json'],true);
			$a_val['problem_list'] = $problem_list;
			$a_val['answer_content'] = '';

			foreach($a_val['answer_json'] as $b_key=>$b_val){
				if (is_array($b_val['content'])) {
					$a_val['answer_content'] .= $a_val['problem_list'][$b_val['problem_id']]['problem_name'] . join(':', $b_val['content']) . "<br>";
				} else {
					$a_val['answer_content'] .= $a_val['problem_list'][$b_val['problem_id']]['problem_name'] . $b_val['content'] . "<br>";
				}
				$a_val['problem_list'][$b_val['problem_id']]['content'] = $b_val['content'];
			}
			$a_val['problem_list'] = array_values($a_val['problem_list']);
			$list[$a_key] = $a_val;
		}
		$data = [
			'count' => $count,
			'list' => $list
		];
		return $data;
	}
}

?>
